import { ref } from 'vue';
import { defineStore } from 'pinia';

import {
  appUserGetInfoService,
  appUserRefreshTokenService
} from '@/apis/appuser';

import { formatDateTime } from '@/utilities/common';
import { baseURL } from '@/utilities/request';

export const useAppUserStore = defineStore(
  'app-user',
  () => {
    const tokenObj = ref({});

    const setTokenObj = (newTokenObj) => (tokenObj.value = newTokenObj);
    const removeTokenObj = () => {
      tokenObj.value = {};
    };

    const userInfo = ref({});
    const getUserInfo = async () => {
      let res = await appUserGetInfoService();
      userInfo.value = res.data;
      if (userInfo.value.headImage) {
        userInfo.value.headImage = `${baseURL}${userInfo.value.headImage}`;
      }
    };
    const setUserInfo = (newUserInfo) => {
      userInfo.value = newUserInfo;
    };

    const isHasUserToken = () => {
      return tokenObj.value.token;
    };

    const isUserTokenValid = () => {
      if (!tokenObj.value || !userInfo.value) {
        return false;
      }

      if (!tokenObj.value.tokenExpireTime) {
        return false;
      }

      let nowStr = formatDateTime(new Date(), 'yyyy/MM/dd HH:mm:ss');
      return nowStr < tokenObj.value.tokenExpireTime;
    };

    const refreshToken = async () => {
      if (!tokenObj.value || !tokenObj.value.refreshTokenExpireTime) {
        return false;
      }

      let nowStr = formatDateTime(new Date(), 'yyyy/MM/dd HH:mm:ss');
      if (nowStr >= tokenObj.value.refreshTokenExpireTime) {
        return false;
      }

      let res = await appUserRefreshTokenService({
        refreshToken: tokenObj.value.refreshToken
      });
      setTokenObj(res.data);
      return true;
    };

    return {
      tokenObj,
      setTokenObj,
      removeTokenObj,
      userInfo,
      getUserInfo,
      setUserInfo,
      isHasUserToken,
      isUserTokenValid,
      refreshToken
    };
  },
  {
    persist: true
  }
);
